package com.moqianfan.mcuassistant.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.moqianfan.mcuassistant.R;
import com.moqianfan.mcuassistant.bean.User;
import com.moqianfan.mcuassistant.utils.LogUtil;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.LogInListener;
import cn.bmob.v3.listener.UpdateListener;

/**
 * Created by Administrator on 2017/6/13.
 * 登陆
 */

public class LoginActivity extends BaseActivity {
    @BindView(R.id.edit_user_name)
    EditText editName;
    @BindView(R.id.edit_user_password)
    EditText editPass;

    private PopupWindow popupWindow;
    private ProgressDialog dialog;

    private String TAG = "LoginActivity";

    @Override
    public void findViews() {
        setContentView(R.layout.activity_login);
        EventBus.getDefault().register(this);
    }

    @Override
    public void initViews() {
        dialog = new ProgressDialog(this);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setMessage("正在登陆，请稍后...");
    }

    @Override
    public void initDatas() {

    }

    @Subscribe
    public void getUser(User user) {
        LogUtil.e(TAG, "收到数据=" + user.getUsername());
        editName.setText(user.getUsername());
    }

    @OnClick({R.id.btn_login, R.id.txt_register, R.id.txt_login_reset})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.btn_login:
                login();
                break;
            case R.id.txt_register:
                openActivity(RegisterActivity.class);
                break;
            case R.id.txt_login_reset:
                showReset(view);
                break;
        }
    }

    private void login() {
        if (TextUtils.isEmpty(editName.getText().toString())) {
            showToastShort("用户名不能为空");
            return;
        }
        if (TextUtils.isEmpty(editPass.getText().toString())) {
            showToastShort("密码不能为空");
            return;
        }

        if (null != dialog && !dialog.isShowing())
            dialog.show();
        User.loginByAccount(editName.getText().toString(), editPass.getText().toString(),
                new LogInListener<User>() {
                    @Override
                    public void done(User bmobUser, BmobException e) {
                        if (null == e) {
                            sendMsg("登陆成功", 0x123, handler);
                            user = bmobUser;

                            MobclickAgent.onProfileSignIn(User.getCurrentUser().getEmail());
                        } else {
                            LogUtil.d(TAG, e.toString());
                            switch (e.getErrorCode()) {
                                case 101:
                                    sendMsg("用户名或密码错误", 0x124, handler);
                                    break;
                            }
                        }
                    }
                });
    }

    /**
     * 重置密码对话框
     *
     * @param parent 打开对话框view
     */
    public void showReset(View parent) {

        LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = layoutInflater.inflate(R.layout.view_pop_comm, null);
        TextView title = (TextView) view.findViewById(R.id.txt_pop_title);
        title.setText("重置密码");
        final EditText edit1 = (EditText) view.findViewById(R.id.edit_pop_value1);
        edit1.setHint("请输入邮件地址");
        EditText edit2 = (EditText) view.findViewById(R.id.edit_pop_value2);
        edit2.setVisibility(View.GONE);
        Button btnCalcel = (Button) view.findViewById(R.id.btn_no);
        btnCalcel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != popupWindow && popupWindow.isShowing())
                    popupWindow.dismiss();
            }
        });
        Button btnYes = (Button) view.findViewById(R.id.btn_yes);
        btnYes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                resetPass(edit1.getText().toString());
                if (null != popupWindow && popupWindow.isShowing())
                    popupWindow.dismiss();
            }
        });

        popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);

        // 使其聚集
        popupWindow.setFocusable(true);
        // 设置允许在外点击消失
        popupWindow.setOutsideTouchable(false);

        // 这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        // 显示的位置为:屏幕的宽度的一半-PopupWindow的高度的一半
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.6f;
        getWindow().setAttributes(lp);
        popupWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });
    }

    /**
     * 发送邮件进行重置密码
     *
     * @param email 邮件地址
     */
    private void resetPass(final String email) {
        if (TextUtils.isEmpty(email)) {
            sendMsg("邮件地址不能为空", 0x124, handler);
            return;
        }
        User.resetPasswordByEmail(email, new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    sendMsg("重置密码请求成功，请到" + email + "邮箱进行密码重置操作", 0x125, handler);
                } else {
                    LogUtil.w(TAG, e.toString());
                    sendMsg("失败：" + e.getMessage(), 0x125, handler);
                }
            }
        });
    }

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            Bundle b = msg.getData();
            switch (msg.what) {
                case 0x123:
                    showToastShort(b.getString("msg"));
                    openActivity(MainActivity.class);
                    finish();
                    break;
                case 0x124:
                    showToastShort(b.getString("msg"));
                    break;
                case 0x125:
                    showToastLong(b.getString("msg"));
                    break;
            }
            if (null != dialog && dialog.isShowing())
                dialog.dismiss();
            return true;
        }
    });

    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出程序",
                        Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                android.os.Process.killProcess(android.os.Process.myPid());   //获取PID
                System.exit(0);
                finish();
            }
        }
        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
